<?php

/**
 * Created by PhpStorm.
 * User: Jie
 * Date: 5/18/2016
 * Time: 10:30 AM
 */
class OrderexportController extends \Core_BackendCtl
{
    public function indexAction()
    {
        //显示订单导出功能

        // 读取文件上传路径
        $dir = $this->getFileDir();
        // 获取已经导出的文件数组
        $fileData = $this->displayFile($dir);
        // 将数组逆转
        $fileData = $this->bubbleSort($fileData);

        $this->_view->assign("pageTitle", '数据导出');
        $this->_view->assign("filedata", $fileData);
    }

    //处理导出方法
    public function dealExportTaskAction()
    {
        // 接收数据
        $start = $this->getp('start_time');
        $end = $this->getp('end_time');

        // 筛选数据
        if (empty($start) || empty($end)) {
            $this->error('开始时间和结束时间不能为空，请重新选择', 'ErrorMessage');
            //return;
        }
        if ($start > $end) {
            $this->error('开始时间必须小于结束时间，请重新选择', 'ErrorMessage');
            return;
        }
        //print_r($this->getAllPost());exit;


        // 读取文件上传路径
        $dir = $this->getFileDir();

        // 组织保存文件名
        $outputFN = 'orderinfo_' . substr($start, 0, 10) . '_' . substr($end, 0, 10) . '.xlsx';

        $exist_file = $this->scanFile($dir, $outputFN);
        // 如果存在相同的文件
        if ($exist_file) {
            //Tools_help::setSession('已经导出过文件，请检查!', 'ErrorMessage');
            $this->downFile($dir, $outputFN);
            return;
        } else {
            // 进行导出任务
            $this->orderInfoExport($start, $end, $outputFN);
        }
        exit;
    }

    //导出Excel表格功能
    public function orderInfoExport($start, $end, $filename)
    {
        $tmp = 0;
        //实例化
        $orderModel = new OrderModel();

        //获取结果数组
        if (!strstr($end, '23:59:59')) {
            $end = $end . ' 23:59:59';
        }

        $orderRecord = $orderModel->getOrderInTime($start, $end);
        //var_dump($orderRecord);exit;
        //excel文件导出
        //设置无限制时间
        set_time_limit(0);
        //实例化
        $objExcel = new PHPExcel();

        //导出第一个表格
        $objExcel->setActiveSheetIndex(0);
        $objExcel->getActiveSheet()->setTitle("大发搬家公司订单报表");
        //设置宽度
        $objExcel->getActiveSheet()->getColumnDimension()->setAutoSize(true);
        //设置参数
        $objExcel->getActiveSheet()->setCellValueExplicit('A1', '订单号');
        $objExcel->getActiveSheet()->setCellValueExplicit('B1', '订单来源', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('C1', '搬家业务', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('D1', '联系人', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValue('E1', '客户手机');
        $objExcel->getActiveSheet()->setCellValueExplicit('F1', '领班人员', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('G1', '司机', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValue('H1', '总共价格');
        $objExcel->getActiveSheet()->setCellValue('I1', '应付价格');
        $objExcel->getActiveSheet()->setCellValue('J1', '已支付金额');
        $objExcel->getActiveSheet()->setCellValue('K1', '确认尾款');
        $objExcel->getActiveSheet()->setCellValueExplicit('L1', '订单状态', PHPExcel_Cell_DataType::TYPE_STRING);
        $objExcel->getActiveSheet()->setCellValueExplicit('M1', '订单时间', PHPExcel_Cell_DataType::TYPE_STRING);

        foreach ($orderRecord as $k => $order) {
            $tmp = $k + 2;
            $objExcel->getActiveSheet()->setCellValue('A' . $tmp, $order['order_number']);
            if ($order['order_place'] == 2) {
                $objExcel->getActiveSheet()->setCellValue('B' . $tmp, '后台');
            } else {
                $objExcel->getActiveSheet()->setCellValue('B' . $tmp, '微信');
            }
            $objExcel->getActiveSheet()->setCellValue('C' . $tmp, $order['carry_type']);
            $objExcel->getActiveSheet()->setCellValue('D' . $tmp, $order['client_name']);
            $objExcel->getActiveSheet()->setCellValue('E' . $tmp, $order['client_phone']);
            $objExcel->getActiveSheet()->setCellValue('F' . $tmp, $order['foreman']);
            $objExcel->getActiveSheet()->setCellValue('G' . $tmp, $order['driver_name']);
            $objExcel->getActiveSheet()->setCellValue('H' . $tmp, $order['total_price']);
            $objExcel->getActiveSheet()->setCellValue('I' . $tmp, $order['must_price']);
            $objExcel->getActiveSheet()->setCellValue('J' . $tmp, $order['already_price']);
            $objExcel->getActiveSheet()->setCellValue('K' . $tmp, $order['final_payment']);
            switch ($order['order_state']) {
                case '0':
                    $objExcel->getActiveSheet()->setCellValue('L' . $tmp, '未确认');
                case '1':
                    $objExcel->getActiveSheet()->setCellValue('L' . $tmp, '已确认');
                case '2':
                    $objExcel->getActiveSheet()->setCellValue('L' . $tmp, '已派工');
                case '3':
                    $objExcel->getActiveSheet()->setCellValue('L' . $tmp, '完成');
                case '-2':
                    $objExcel->getActiveSheet()->setCellValue('L' . $tmp, '退款');
            }
            $objExcel->getActiveSheet()->setCellValue('M' . $tmp, date('Y-m-d H:i:s', $order['createtime']));
        }
        //生成07文档
        $xlsWriter = new PHPExcel_Writer_Excel2007($objExcel);
        $config = \Yaf_Registry::get('configarr');
        $url = $config['application']['site']['uploadUri'];
        $dir = PUBLIC_PATH.$url.'excel/';
        $dir = str_replace("//", "/", $dir);
        $xlsWriter->save($dir.$filename);
        //添加成功提示
        Tools_help::setSession('Message', '导出文档成功,请自行下载');
        $this->redirect(Tools_help::url('backend/orderexport/index'));
    }

    //显示已经导出的文件
    public function displayFile($dir)
    {
        $arr_file = null;
        //$dir = str_replace('/','\\',$dir);
        if (is_dir($dir)) {
            //如果是路径才遍历文件
            if ($dh = opendir($dir)) {
                while (false !== ($file = readdir($dh))) {
                    if ($file != '.' && $file != '..') {
                        $arr_file[] = array('name' => Tools_help::fbu('attachs/excel/' . $file), 'ctime' => filemtime($dir . $file));
                    }
                }
            }
            closedir($dh);
        }
        clearstatcache();
        return $arr_file;
    }

    //为文件排序
    public function bubbleSort(&$arr_file)
    {
        $cnt = count($arr_file);
        for ($i = 0; $i < $cnt; $i++) {
            for ($j = 0; $j < $cnt - $i - 1; $j++) {
                if (strcmp($arr_file[$j]['ctime'], $arr_file[$j + 1]['ctime'])) {
                    $temp = $arr_file[$j];
                    $arr_file[$j] = $arr_file[$j + 1];
                    $arr_file[$j + 1] = $temp;
                }
            }
        }

        return $arr_file;
    }

    //文件遍历方法
    //return:bool，如果有相同的文件，返回true，反之false
    public function scanFile($dir, $outputFN)
    {
        $arr_file = null;
        if (is_dir($dir)) {
            //如果是路径才遍历文件
            if ($dh = opendir($dir)) {
                while (false !== ($file = readdir($dh))) {
                    //发现有相同的文件
                    if ($file == $outputFN) {
                        return true;
                    }
                }
            }
            closedir($dh);
        }
        return false;
    }

    // 读取文件上传路径
    public function getFileDir()
    {
        $config = \Yaf_Registry::get('configarr');
        $url = $config['application']['site']['uploadUri'];
        $dir = PUBLIC_PATH . $url . 'excel/';
        $dir = str_replace("//", "/", $dir);

        return $dir;
    }

    //文件下载
    public function downFile($file_dir, $file_name)
    {
        //打开文件
        $file = fopen($file_dir . $file_name, "r");
        //输入文件标签
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($file_dir . $file_name));
        Header("Content-Disposition: attachment; filename=" . $file_name);
        //输出文件内容
        //读取文件内容并直接输出到浏览器
        echo fread($file, filesize($file_dir . $file_name));
        fclose($file);
        exit ();
    }
}